package com.ctsi.commons.util.zip;

import com.ctsi.commons.util.UtilFile;
import com.ctsi.commons.util.UtilMisc;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipImpl implements Zip {

	public void dozip(String zipout, String file, String base) throws Exception {
		OutputStream fileout = UtilFile.getBufferedOutputStream(zipout);
		File f = new File(file);
		ZipOutputStream out = new ZipOutputStream(fileout);
		try {
			this.dozip(out, f, base);
		} finally {
			out.close();
		}

	}

	public void dozip(String zipout, File f, String base) throws Exception {
		OutputStream fileout = UtilFile.getBufferedOutputStream(zipout);
		ZipOutputStream out = new ZipOutputStream(fileout);
		try {
			this.dozip(out, f, base);
		} finally {
			out.close();
		}

	}

	public void dozip(String zipout, InputStream in, String base) throws Exception {
		OutputStream fileout = UtilFile.getBufferedOutputStream(zipout);
		ZipOutputStream out = new ZipOutputStream(fileout);
		try {
			out.putNextEntry(new ZipEntry(base));
			UtilFile.copyNoClose(in, out);
			out.closeEntry();
		} finally {
			UtilMisc.closeObjNoExc(in);
			UtilMisc.closeObjNoExc(out);
		}

	}

	public void dozip(ZipOutputStream zipStream, InputStream in, String base) throws IOException {
		zipStream.putNextEntry(new ZipEntry(base));

		UtilFile.copyNoClose(in, zipStream);
		zipStream.closeEntry();
		in.close();

	}

	public void dozip(ZipOutputStream out, File f, String base) throws Exception {
		if (f.isDirectory()) {
			File[] fl = f.listFiles();

			// out.putNextEntry(new ZipEntry(base + File.separator));

			base = base == null ? "" : base + File.separator;
			// System.out.println(base);
			for (int i = 0; i < fl.length; i++) {
				dozip(out, fl[i], base + fl[i].getName());
			}
			// out.closeEntry();
		} else {
			out.putNextEntry(new ZipEntry(base));
			try (FileInputStream in = new FileInputStream(f)) {
				UtilFile.copyNoClose(in, out);
				out.closeEntry();
			}

		}
	}

}
